package nina.yiyou.attendance.s10merge.input

import nina.yiyou.salary.input.util.CellValueGetter
import nina.yiyou.salary.input.util.ExcelReadOpener
import nina.yiyou.salary.input.util.HeaderMapMaker
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.ss.usermodel.Sheet
import org.apache.poi.ss.usermodel.Workbook

import java.nio.file.Path
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.stream.Collectors
import java.util.stream.IntStream

class AttendLeaveExcelReader {

  interface Line {

    String employeeName()

    String leaveType()

    LocalDateTime startTime()

    LocalDateTime endTime()

    double leaveDuration()

    boolean isValid()
  }

  AttendLeaveExcelReader(Path excelPath) {
    _excelPath = excelPath
  }

  Map<String, List> read() {
    Workbook workbook = new ExcelReadOpener(_excelPath).openXlsx()
    Map result = readNameLinesMap(workbook.getSheetAt(0))
    workbook.close()
    return result
  }

  private Map<String, List> readNameLinesMap(Sheet sheet) {
    Map<Integer, String> header = new HeaderMapMaker(sheet.getRow(0)).make()
    def getCellVal = { Row r, int c -> new CellValueGetter(r.getCell(c)).get() }

    return IntStream.rangeClosed(1, sheet.lastRowNum)
        .mapToObj { sheet.getRow(it) }
        .map { header.collectEntries { col, head -> [head, getCellVal(it, col)] } as Map }
        .map { makeLine(it) }
        .filter { it.isValid() }
        .collect(Collectors.groupingBy { Line l -> l.employeeName() })
  }

  private Line makeLine(Map lineMap) {
    def strVal = { String k -> lineMap[k] as String }
    def timeVal = { String k -> LocalDateTime.parse(strVal(k), DATE_FMT) }

    return new Line() {
      @Override
      String employeeName() {
        return lineMap['申请人']
      }

      @Override
      String leaveType() {
        return lineMap['请假类型2'] ?: lineMap['请假类型']
      }

      @Override
      LocalDateTime startTime() {
        return timeVal('开始时间')
      }

      @Override
      LocalDateTime endTime() {
        return timeVal('结束时间')
      }

      @Override
      double leaveDuration() {
        return Double.parseDouble(strVal('请假时长').replace('小时', ''))
      }

      @Override
      boolean isValid() {
        return lineMap['当前审批状态'] == '已通过'
      }
    }
  }

  private static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern('yyyy/M/d HH:mm')

  private final Path _excelPath
}
